<template>
  <div>
    <div class="flex items-center px-[3px] mb-[10px]">
      <div
        class="text-[var(--el-text-color-primary)] text-[13px] whitespace-nowrap mr-[10px]"
      >
        请求方式
      </div>
      <el-select
        :teleported="false"
        v-model="queryType"
        size="default"
        placeholder="Select"
        @change="changeType"
      >
        <el-option label="静态数据" value="static" />
        <el-option label="动态接口" value="dynamic" />
      </el-select>
    </div>
    <div v-if="queryType == 'static'">
      <el-scrollbar max-height="500" class="mb-[20px]">
        <div
          class="w-[280px] my-[0px] rounded-[10px] select-text mx-auto p-[10px] bg-[#1c1b1b] text-[#ccc]"
        >
          {{ staticData }}
        </div>
      </el-scrollbar>
      <div class="w-[70%] mx-auto flex items-center justify-around">
        <el-button icon="Edit" color="#706969" @click="openJsonEdit"
          >编辑</el-button
        >
        <el-button icon="BottomLeft" color="#706969" @click="importCode"
          >导入</el-button
        >
        <el-button icon="Download" color="#706969" @click="exportCode"
          >导出</el-button
        >

        <jsonEditDialog
          ref="jsonRef"
          :staticData="staticData"
          @updateStaticData="updateStaticData"
          @close="closeJsonEdit"
        />
      </div>
    </div>
    <div v-if="queryType == 'dynamic'">
      <BaseRequestModule
        @openEdit="openEdit"
        :layoutItem="layoutItem"
        v-model:request="layoutItem.request"
        @sendQuery="sendQuery"
      />
      <div class="mt-[20px] relative">
        <!-- 310px -->
        <el-steps
          :style="{
            height: layoutItem.eventMethods.ifFilter ? '310px' : '160px',
          }"
          direction="vertical"
          :active="2"
          process-status="wait"
          finish-status="wait"
        >
          <el-step
            title="数据过滤"
            description="过滤器默认处理接口返回的data字段"
          >
            <template #icon>
              <el-icon size="24" class="bg-[#232324]"
                ><CircleCheckFilled
              /></el-icon>
            </template>
          </el-step>

          <el-step title="数据内容" description="过滤器处理以后的数据">
            <template #icon>
              <el-icon size="24" class="bg-[#232324]"
                ><CircleCheckFilled
              /></el-icon> </template
          ></el-step>
        </el-steps>

        <div
          v-if="layoutItem.eventMethods.ifFilter"
          class="absolute top-[55px] left-[30px]"
        >
          <div
            class="w-[250px] relative h-[200px] rounded-md my-[0px] mx-auto p-[10px] bg-[#1c1b1b] text-[#ccc]"
          >
            <el-scrollbar height="200">
              <div>
                {{ layoutItem.eventMethods.filterMethod }}
              </div>
            </el-scrollbar>
            <div class="absolute bottom-[10px] right-[8px]">
              <el-button
                class="ml-[10px]"
                type="primary"
                size="small"
                icon="Edit"
                color="#3a89fe"
                @click="openFilter"
                >编辑</el-button
              >
              <el-button
                class="ml-[10px]"
                type="info"
                size="small"
                @click="cancelFilter"
                >删除</el-button
              >
            </div>
          </div>
        </div>
        <el-button
          v-else
          class="ml-[10px] absolute top-[55px] left-[30px]"
          type="primary"
          size="default"
          icon="Filter"
          color="#3a89fe"
          @click="openFilter"
          >新增过滤器</el-button
        >
        <el-scrollbar :height="250">
          <div
            class="w-[250px] overflow-hidden mt-[10px] h-[auto] rounded-md my-[0px] mx-auto p-[10px] bg-[#1c1b1b] text-[#ccc]"
          >
            {{ layoutItem?.responseData || "暂无数据" }}
          </div>
        </el-scrollbar>
      </div>
      <RequestModule
        ref="requestRef"
        v-if="showRequestRef"
        :layoutItem="layoutItem"
        :request="layoutItem.request"
        @save="save"
        @saveSource="saveSource"
        @close="closeRequest"
      />
      <DataFilterDialog
        ref="dataFilterRef"
        :orginResponse="orginResponse"
        :resData="requestResponse"
        :filterMethod="layoutItem.eventMethods.filterMethod"
        @updateData="updateFilterMethod"
        @close="closeFilter"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, inject, nextTick } from "vue";
import DataFilterDialog from "@renderer/components/dataFilterDialog/index.vue";
import RequestModule from "@renderer/components/RequestModule/requestDialog.vue";
import BaseRequestModule from "@renderer/components/RequestModule/base.vue";
import jsonEditDialog from "./jsonEditDialog.vue";
import Serves from "@renderer/utils/requestNew";
import { exportStaticData, importFile } from "@renderer/utils/operationCode";
import { generateFilterFunc } from "@renderer/hooks/useEvents";
import { filterMethod } from "@renderer/utils/eventMethods";

import { useDataSource } from "@renderer/hooks/useDataSource";
import { getDataSourceDetail } from "@renderer/api/dataSource";
import { handelResponseData } from "@renderer/utils/handleResponseData";
import { deepClone } from "@renderer/utils/other";
interface PropsType {
  layout: any;
}

let props = withDefaults(defineProps<PropsType>(), {
  layout: {},
});
const emit = defineEmits(["update:layout"]);
const { updateCanShortKey } = inject("canShortKey") as any;
let queryType = ref("dynamic");
let layoutItem = computed({
  get() {
    return props.layout;
  },
  set() {
    emit("update:layout");
  },
});
const requestResponse = ref();
let dataFilterRef = ref(null);
let requestRef = ref(null);
let showRequestRef = ref(false);
let jsonRef = ref(null);
let staticData = ref(
  JSON.parse(JSON.stringify(layoutItem.value.staticData || {})) || {}
);

watch(
  () => props.layout,
  () => {
    staticData.value = props.layout.staticData;
  }
);

let showJson = ref(false);
const openEdit = () => {
  showRequestRef.value = true;
  nextTick(() => {
    requestRef.value.dialogVisible = true;
    requestRef.value.init(layoutItem.value.request);
    updateCanShortKey(false);
  });
};
const save = (value) => {
  layoutItem.value.request = value;
  // console.log("value!!!!!!!", value);
  updateCanShortKey(true);
};
const closeRequest = () => {
  showRequestRef.value = false;
  updateCanShortKey(true);
};

const saveSource = (value) => {
  layoutItem.value.dataSourceId = value.dataSourceId;
  layoutItem.value.ifDataSource = value.ifDataSource;
  layoutItem.value.dataSourceInfo = JSON.parse(
    JSON.stringify(value.dataSourceInfo)
  );
  // console.log("value", value);
};
const openJsonEdit = () => {
  showJson.value = true;
  jsonRef.value.dialogVisible = true;
  updateCanShortKey(false);
};

const closeJsonEdit = () => {
  showJson.value = false;
  updateCanShortKey(true);
};
watch(
  staticData,
  (val) => {
    // console.log("static", val);
    // layoutItem.value.responseData = val;
    layoutItem.value.staticData = val;
  },
  {
    immediate: true,
    deep: true,
  }
);
let cashedData = ref<any>(null);
const updateStaticData = (val: any) => {
  staticData.value = val;
  updateCanShortKey(true);
  layoutItem.value.staticData = val;
  layoutItem.value.responseData = val;
  layoutItem.value.props = handelResponseData(val, layoutItem.value);
};

const changeType = (type: string) => {
  if (queryType.value == "static") {
    cashedData.value = deepClone(layoutItem.value.responseData);

    layoutItem.value.responseData = deepClone(layoutItem.value.staticData);
    layoutItem.value.props = handelResponseData(
      layoutItem.value.staticData,
      layoutItem.value
    );
  } else {
    layoutItem.value.responseData = deepClone(cashedData.value);
    layoutItem.value.props = handelResponseData(
      layoutItem.value.responseData,
      layoutItem.value
    );
    cashedData.value = null;
  }
};

const orginResponse = ref(null);
const sendQuery = async (value) => {
  if (!layoutItem.value.ifDataSource && !layoutItem.value.request.baseUrl) {
    ElMessage.error("请配置动态接口信息");
    return;
  }
  try {
    let obj: any = {};
    if (layoutItem.value.ifDataSource) {
      let real_Info: any = await getDataSourceDetail({
        id: layoutItem.value.dataSourceId,
      });
      if (real_Info.code == 200) {
        layoutItem.value.dataSourceInfo = real_Info.data;
      } else {
        ElMessage.error("数据源信息获取失败");
        return;
      }
      obj = await useDataSource(
        layoutItem.value.dataSourceInfo,
        JSON.parse(JSON.stringify(layoutItem.value.request))
      );
    } else {
      obj = JSON.parse(JSON.stringify(layoutItem.value.request));
    }
    console.log("obj", deepClone(obj));
    let request = new Serves(obj.baseUrl).instance;
    if (obj.ifFormData) {
      let formdata = new FormData();
      for (let key in obj.data) {
        formdata.append(key, obj.data[key]);
      }
      obj.data = formdata;
    }
    console.log("obj!!!!!!", obj);
    orginResponse.value = await request(obj);
    const { data } = orginResponse.value;
    ElMessage.success("接口请求成功");
    requestResponse.value = JSON.parse(JSON.stringify(data || {}));
    // 使用自定义的函数过滤器
    layoutItem.value.responseData = generateFilterFunc(
      layoutItem.value.eventMethods.filterMethod,
      requestResponse.value,
      orginResponse.value
    )();
    layoutItem.value.props = handelResponseData(
      layoutItem.value.responseData,
      layoutItem.value
    );
  } catch (err) {
    layoutItem.value.responseData = [];
    ElMessage.error("接口请求失败:" + err);
  }
};

const importCode = async () => {
  let res = await importFile();
  if (res) {
    staticData.value = Object.assign({}, staticData.value, res);
  }
};
const exportCode = () => {
  if (
    staticData.value &&
    Object.keys(staticData.value).length > 0 &&
    layoutItem.value
  ) {
    exportStaticData(
      "静态数据" + layoutItem.value.id,
      JSON.stringify(staticData.value)
    );
  }
};
const openFilter = () => {
  updateCanShortKey(false);
  dataFilterRef.value.dialogVisible = true;
};
const closeFilter = () => {
  dataFilterRef.value.dialogVisible = false;
  updateCanShortKey(true);
};
const cancelFilter = () => {
  layoutItem.value.eventMethods.ifFilter = false;
  layoutItem.value.eventMethods.filterMethod = filterMethod;
};
const updateFilterMethod = (val) => {
  layoutItem.value.eventMethods.filterMethod = val;
  layoutItem.value.eventMethods.ifFilter = true;
  updateCanShortKey(true);
};
</script>

<style scoped lang="scss">
:deep(.el-step__icon) {
  background-color: none !important;
}
</style>
